<template>
     <qh-page-view  :showNavbar="false"
          >
          <!-- <view class="search-box">
               <view class="search-content flex-cn">   
                    <text class="qh-rt-single qh-rt-a-zu2432 search-icon"></text>
                    <input class="search-input" type="text" :focus="isFocus" v-model="searchForm.goods_name" placeholder="请输入商品名称" placeholder-class="pl" @confirm="searchData" />
                    <view class="search-btn flex-cn-cn" @click="searchData">搜索</view>
               </view>
          </view> -->
          <view class="fixed-header" :style="headerStyle">
               <uni-status-bar></uni-status-bar>
               <view class="search-box flex-cn">
                    <view class="navbar-left flex-cn" style="margin-right: 24rpx;margin-left: 24rpx;"
                          :style="styleColor" @click="backHome">
                         <view class="qh-rt-single qh-rt-zuo-zuo navbar-back-icon"> </view>
                    </view>

                    <view class="search-content flex-cn" @click="toSearchGoods">
                         <text class="qh-rt-single qh-rt-a-zu2432 search-icon"></text>
                         <view class="search-input">请输入商品名称</view>
                         <!-- <view class="search-btn flex-cn-cn">搜索</view> -->
                    </view>
                    <view style="width: 60rpx;"></view>
               </view>
          </view>

          <qh-tabs ref="labelRef" style="position:static;top:10rpx; background-color: #fff;border-radius: 16rpx 16rpx 0"
               v-model="actLabelId" :list="labelList" keyField="id" actLineBreak itemActColor="var(--primary-color)"
               itemActStyle="font-weight: bold" :bottomLine="true" lineColor="var(--primary-color)" lineWidth="40"
               @change="searchGoods">
          </qh-tabs>


          <view class="flex-column-100">
               <scroll-view scroll-y="true" @scroll="onScroll" class="scroll-view" :show-scrollbar="false"
                    @scrolltolower="getGoodsList" refresher-enabled @refresherrefresh="pullDownRefresh"
                    :refresher-triggered="isRefresh" refresher-background="transparent">
                    <view class="scroll-view-content">
                         <!-- 商品列表搜索 VIP4-->
                         <view style="background-color: #fff;" class="goods-list-box  flex-wrap">
                              <waterfallsFlow ref="WaterfallRef" :keyIndex="actLabelId" :wfList="goodsList"
                                   :updateNum="searchForm.page"></waterfallsFlow>
                              <!-- <waterfallsFlow ref="WaterfallRef"  :keyIndex="actLabelId"  :wfList="goodsList" :updateNum="searchForm.page"  ></waterfallsFlow> -->
                              <view class="flex-cn-cn">
                                   <view   style="width: 100%;height: 60rpx;" v-if="canLoad && isLoading" class="bottom-message flex-cn-cn">加载中...</view>
                                   <view  v-if="!canLoad && !isLoading" class="flex-cn-cn bottom-message">
                                      
                                        <template v-if="goodsList.length === 0">
                                             <view style="padding: 10rpx; display: flex;flex-direction: column;align-items: center;">
                                                  <image style="width: 326rpx; height: 280rpx;" src="https://xzthealth-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/174099354667c5740a95e14.png"></image>
                                                  <text style="margin: 20rpx 0;">当前数据正在成长中</text>
                                                  <text>稍后再来看看吧～</text>
                                             </view>
                                        </template>
                                                                           <template v-else>
                                             <view class="line"></view>
                                             <text class="mar_l_10 mar_r_10">没有更多了</text>
                                             <view class="line"></view>
                                        </template>
                                   </view>
                              </view>
                         </view>
                    </view>
               </scroll-view>
          </view>
          <!-- 购物车图钉 -->
          <shopping-pushpins></shopping-pushpins>
          <!-- 选择规格弹窗 -->
          <block v-if="showSelectSku">
               <choose-sku :sku="sku" :goodsinfo="goods" :goodsType="'1'" @close="closeSku"
                    @sku-change="handleSkuChange"></choose-sku>
          </block>
     </qh-page-view>
</template>

<script>
const app = getApp().globalData;
export default {
     data() {
          return {
               opacity: 1,
               isTop: true, // 用于标记是否在顶部
               labelList: [],
               defaultActLabelId: null,  //默认ID
               actLabelId: "", //选中的标签id
               goodsChecked: [],
               animations: [],
               animationIndex: null,
               indexes: [],
               isFocus: false,
               title: "",
               goodsList: [],
               isRefresh: false,
               isLoading: false,
               canLoad: true,
               firstLoad: true,
               searchForm: {
                    goods_name: "",
                    person1: "",
                    person2: "",
                    person3: "",
                    page: 1,
                    limit: 10,
               },
               showSelectSku: false,
               goods: {},
               sku: {},
          };
     },
     /**
      * @param {Object} options
      * name		分类名称
      * type		分类级别  1、2、3 不传默认为1
      * id		分类id
      */
     async onLoad(options) {
          //     1-功能保健 2-滋补品 3-营养补充 4-礼尚往来
          await this.getLabelList(options.select_id)

          // 确保在标签列表加载完成后再设置选中项
          await this.$nextTick();



          // 优先使用传入的标签ID
          if (options.label_id) {
               if (options.label_id == -1) {
                    this.actLabelId = this.labelList[0].id;
                    this.defaultActLabelId = this.labelList[0].id;
               } else {
                    this.actLabelId = options.label_id;
                    this.defaultActLabelId = options.label_id;
               }

          } else if (options.id) {
               this.actLabelId = options.id;
               this.defaultActLabelId = options.id;
          } else if (options.label_id == -1) {
               this.actLabelId = this.labelList[0].id;
               this.defaultActLabelId = this.labelList[0].id;
          }

          await this.$onLaunched;
          if (options.search == 1) {
               this.$nextTick(() => {
                    this.isFocus = true;
               });
               this.title = "搜索商品";
          } else {
               this.title = options.name ? options.name : "商品列表";
               if (options.id) {
                    switch (options.type) {
                         case "2":
                              this.searchForm.person2 = options.id;
                              break;
                         case "3":
                              this.searchForm.person3 = options.id;
                              break;
                         default:
                              this.searchForm.person1 = options.id;
                              break;
                    }
               }
          }

          // 只调用一次搜索
          await this.searchGoods({ id: this.actLabelId });
     },
     computed: {
          headerStyle() {
               return `background-image: ${'url("https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/1735370856676fa86844a21.png")' }`
          },
          styleColor() {
               return `color: ${this.isTop ? '#fff' : '#fff '}`
          }
     },

     onShow() {
          if (this.$refs.WaterfallRef) {
               this.$refs.WaterfallRef.upDate()
          }
     },
     methods: {


          toSearchGoods() {
               console.log()
               uni.navigateTo({
                    url: "/pages/mer/goods/search/search?search=1",
               });
          },
          //后退
          backHome() {
               uni.navigateBack();
          },
          //搜索
          async searchGoods(e) {
               this.actLabelId = e.id
               this.title = e.name
               this.searchForm.page = 1
               this.canLoad = true;
               this.defaultActLabelId = e.id
               this.getGoodsList();
          },

          //滚动监听
          onScroll(event) {
               const scrollTop = event.detail.scrollTop;
               this.isTop = scrollTop <= 40;
               this.opacity = Math.max(1 - scrollTop / 100, 0);
               this.isTop = scrollTop <= 100;
               if (scrollTop < 50) this.opacity = 1;
               // console.log( this.isTop   , ' this.isTop ')
          },


          // 1-功能保健 2-滋补品 3-营养补充 4-礼尚往来
          async getLabelList(industryId) {
               const { data, status } = await this.$request(
                    'SmallProgramApi/ShiFu/getHomePageGoodLabel',
                    { store_id: this.$store.mallStoreId, industry_id: industryId }
               )
               if (status == 1) {
                    // Store the data directly without any filtering
                    // this.labelList = data;
                    // if (data.length) {
                    //      await this.$nextTick();
                    //      if (this.$refs.labelRef) {
                    //           this.$refs.labelRef.marginLeft = 0;
                    //      }
                    // }
                    this.labelList = data;
                    if (data.length) {
                         this.$nextTick(() => {
                              this.$refs.labelRef && (this.$refs.labelRef.marginLeft = 0);
                              this.defaultActLabelId = data[0].id
                              this.actLabelId == undefined ? this.actLabelId = data[0].id : this.actLabelId
                         });
                    }
               }
          },

          //查看商品详情
          toDetail(id) {
               uni.navigateTo({
                    url: "/pages/mer/goods/details/details?id=" + id,
               });
          },
          //下拉刷新
          async pullDownRefresh() {
               this.isRefresh = true;
               await this.searchData();
               // await this.getLabelList()
               this.isRefresh = false;
          },
          async searchData() {
               this.canLoad = true;
               this.isLoading = false;
               this.searchForm.page = 1;
               await this.getGoodsList();

          },


          //关闭规格弹窗
          closeSku() {
               this.showSelectSku = false;
          },
          //添加商品到购物车
          async addToCar(index) {
               if (this.goodsList[index].attribute == 2) {
                    this.goods = {
                         ...this.goodsList[index],
                         goods_image: this.goodsList[index].path,
                         goods_num: 999,
                    };
                    this.showSelectSku = true;
               } else {
                    const res = await this.$mutations.setShoppingCar(
                         {
                              goods_id: this.goodsList[index].goods_id,
                              num: 1,
                         },
                         1
                    );
                    if (res) {
                         this.showSelectSku = false;
                    }
               }
          },
          //点击搜索
          search() {
               uni.navigateTo({
                    url: "../product/productList/productList?type=1",
               });
          },
          //获取商品
          getGoodsList() {
               return new Promise(async (resolve) => {
                    if (this.isLoading || !this.canLoad) return resolve(false);
                    this.isLoading = true;
                    this.searchForm = Object.assign(this.searchForm, { store_id: this.$store.mallStoreId, label_id: this.actLabelId })
                    const { status, data, message } = await this.$request(
                         "SmallProgramApi/ShiFu/getLabelGoodList",
                         this.searchForm
                    );

                    if (this.firstLoad) {
                         this.firstLoad = false;
                    }
                    if (status != 1)
                         return (
                              uni.showToast({
                                   title: message,
                                   icon: "none",
                              }) && resolve(false)
                         );
                    if (this.searchForm.page == 1) {
                         this.goodsList = [...data];
                    } else {
                         this.goodsList = [...this.goodsList, ...data];


                    }

                    if (!data.length) {
                         this.canLoad = false;
                    }
                    this.searchForm.page++;
                    // this.canLoad = this.goodsList.length == data ? false : true;

                    this.goodsList.forEach((item) => {
                         let matchedItem = this.$store.merShoppingGoodsList.find(
                              (el) => el.goods_id === item.id
                         );
                         if (matchedItem) {
                              item.num = matchedItem.num;
                         } else {
                              this.indexes = []
                              item.num = 0;
                         }
                    });


                    this.isLoading = false;
                    resolve(true);
               });
          },


          handleSkuChange(skuData) {
               console.log('SKU changed:', skuData);

          },
     },
};
</script>

<style lang="scss">
.fixed-header {
     background-repeat: no-repeat;
     background-size: cover;
     background-position: center;
     background-color: #ffffff;
     position: flex;
     top: 0;
     z-index: 10;
}

.bottom-message {
     color: #ccc;
     font-size: 24rpx;
     // background-color: #fff;
     width: 100%;
     padding: 10rpx 0;
}

.line {
     width: 40%;
     height: 1px;
     background-color: #ccc;
}



.search-box {
     height: 102rpx;
     // padding: 12rpx 24rpx;
     // box-sizing: border-box;
     // box-shadow: 0 0 16rpx rgba(0, 0, 0, 0.05);
     z-index: 1;


     .search-content {
          height: 64rpx;
          width: 448rpx;
          padding: 0 0 0 24rpx;
          border: 2rpx solid var(--primary-color);
          border-radius: 34rpx;
          box-sizing: border-box;
          background-color: #ffffff;

          .search-icon {
               font-size: 28rpx;
               color: #999999;
          }

          .search-input {
               flex: 1;
               font-size: 28rpx;
               line-height: 48rpx;
               color: #333333;
               margin: 0 10rpx;
               height: 48rpx;
          }

          .search-btn {
               width: 124rpx;
               height: 100%;
               font-size: 28rpx;
               color: #ffffff;
               text-align: center;
               line-height: 48rpx;
               // background-color: var(--primary-color);
               border-radius: 32rpx;
               margin-right: -1rpx;
          }
     }
}

.scroll-view {
     // background: #F0F2EE;
     background: #ffffff;

}
</style>
